<template>
  <div>
    <div class="filed" @click="openDialog()">
      <span class="field-value" v-for="(item, key) in fieldValues" :key="key">
        <span>{{ item.label }}</span>
        <span class="el-tag__close el-icon-close icon-close" @click.stop="delFieldValue(item)"></span>
      </span>
      <span class="icon-right el-icon-arrow-right"></span>
    </div>
    <el-dialog
      :custom-class="'org-tree-dialog'"
      :visible.sync="show"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="'请选择'+ title"
      width="50%"
      @close="closeDialog"
      @cancel="closeDialog"
      append-to-body
    >
      <div class="org-tree-box flex-center">
        <div class="left-box">
          <div class="search-input">
            <el-input
              :placeholder="hideTabs.includes('tag') ? '搜索成员、部门' : '搜索成员、部门或标签'"
              v-model="keyword">
              <i slot="prefix" class="el-input__icon el-icon-search" @click="search()"></i>
            </el-input>
          </div>
          <div class="typeTabs">
            <el-tabs v-model="activeTab" @tab-click="changeTab" v-show="!isSearch">
              <el-tab-pane label="组织架构" name="org"  v-if="!hideTabs.includes('org')">
                <div class="tree">
                  <el-tree :props="defaultProps" @node-click="handleNodeClick" @node-expand="expandNode" :data="orgTree"
                           ref="orgTree" node-key="id" :default-expanded-keys=defaultExpandedKeys
                           :expand-on-click-node="false">
                        <span class="custom-tree-node" slot-scope="{ node, data }">
                           <span v-if="!data.leaf" class="icon-org"></span>
                           <span v-if="data.leaf" class="icon-user"></span>
                           <span style="display: flex;align-items: center;" v-if="data.label">
                            <a class="labelH" :title="data.label">{{data.label | ellipsis}}</a>
                            <span v-if="data.totalNum">({{ data.totalNum || 0}})</span>
                          </span>
                           <span class="org-add el-icon-plus" v-if="!data.leaf" :title="'添加整部门'"
                                 @click.stop="checkItem(data,'org')"></span>
                           <span v-if="data.checked" class="item-checked el-icon-check"></span>
                        </span>
                  </el-tree>
                </div>
              </el-tab-pane>
              <el-tab-pane label="标签" name="tag" v-if="!hideTabs.includes('tag')">
                <div class="tag-box">
                  <div class="tag-item" v-for="(item, key) in tags" :key="key" @click="checkItem(item,'tag')">
                    <span class="icon-tag"></span>
                    <span>{{ item.label }}</span>
                    <span v-if="item.checked" class="item-checked el-icon-check"></span>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
            <div class="search-result" v-show="isSearch">
              <div class="result-content" v-if="resultData.length" v-for="(item, key) in resultData" :key="key">
                <template v-if="item.children && item.children.length">
                  <span class="content-type">{{ item.type == 'user' ? '人员' : item.type == 'org' ? '部门' : '标签' }}</span>
                  <div class="content-item" v-for="(r, key) in item.children" :key="key" @click="checkItem(r)">
                    <span :class="'icon-'+ item.type"></span>
                    <span>{{ r.label }}</span>
                    <span class="item-checked el-icon-check" v-if="r.checked"></span>
                  </div>
                </template>
              </div>
              <div v-if="!resultData.length && !isLoading">
                <el-empty description="暂无数据"></el-empty>
              </div>
            </div>
          </div>
        </div>
        <div class="right-box">
          <div class="sel-length">
            已选择的
           {{hideTabs.includes('tag') ? '成员、部门' : '成员、部门或标签'}}
          </div>
          <div class="values-box">
            <div class="value-item" v-for="(item, key) in values" :key="key">
              <span :class="'icon-'+ item.type"></span>
              <span style="padding-left:2px;max-width: 230px;">{{ item.label }}</span>
              <span class="icon-value-delete el-icon-close" @click="deleteItem(item)"></span>
            </div>
          </div>
        </div>
      </div>
      <div class="bottom-box flex-center">
        <el-button class="btn" @click="closeDialog">取 消</el-button>
        <el-button class="btn" type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getUsersByDeptId, pickerSearch} from "@/api/system/user";
import {listTip} from "@/api/system/tip/tipApi";
import {treeselect,treeselectAll} from "@/api/system/dept";

export default {
  filters:{
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 15) {
        return value.slice(0, 15) + "...";
      }
      return value;
    }
  },
  name: "OrgUsers",
  props: {
    title: {
      type: String,
      default: '人员'
    },
    useTreeAll: {
      type: Boolean,
      default: false
    },
    pickArray: {
      type: Array,
      default: []
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    hideTabs:{
      type: Array,
      default: function () {
        return [];
      },
    },
    maxLevel:{
      type: Number,
      default: 0
    }
  },
  model: {
    prop: "pickArray",//定义v-model的值传递给那个prop属性
    event: "change",//定义此事件触发时，自动更新父组件v-model对应的数据
  },
  watch: {
    pickArray: {
      immediate: true,
      handler: function (val) {
        if(val){
          this.fieldValues = val
          this.values = val
        }
      }
    }
  },
  data() {
    return {
      show: false,
      orgTree: [],
      activeTab: 'org',
      keyword: '',
      currentItem: null,
      orgId: null,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultExpandedKeys: [],
      tags: [],
      values: [],
      isSearch: false,
      resultData: [],
      fieldValues: [],
      isLoading: false,
      queryParams: {
        status: '0'
      }
    }
  },
  methods: {
    changeTab() {

    },
    openDialog() {
      if (this.isDisabled) {
        return
      }
      this.keyword = ''
      this.show = true
      this.$nextTick(function () {
        this.search()
      })
    },
    closeDialog() {
      this.show = false
    },
    save() {
      this.show = false
      this.fieldValues = JSON.parse(JSON.stringify(this.values));
      this.$emit('outValue', this.fieldValues)
    },
    delFieldValue(item) {
      if (this.isDisabled) {
        return
      }
      this.deleteItem(item)
      this.fieldValues = JSON.parse(JSON.stringify(this.values));
    },
    updateStatus(){
      this.updateCheckbox(this.orgTree, 'tree')
      this.updateCheckbox(this.tags, 'list')
    },
    search() {
      this.activeTab = 'org'
      if (!this.keyword) {
        this.isSearch = false;
        console.log(this.values)
        if (this.values.length) {
            this.updateStatus()
        }
        return
      }else{
        if (this.values.length) {
          this.updateStatus()
        }
      }
      this.isLoading = true
      this.resultData = []
      pickerSearch(this.keyword).then(res => {

        if (res.code == '200') {
          this.isLoading = false
          if (res.rows && res.rows.length) {
            let orgs = res.rows.filter(item => item.flag == 1).map(item => {
              return {id: item.id, label: item.name, type: 'org'}
            })
            if (orgs.length) {
              this.resultData.push({
                type: 'org',
                children: orgs
              })
            }
            let users = res.rows.filter(item => item.flag == 0).map(item => {
              return {id: item.id, label: item.name, type: 'user'}
            })
            if (users.length) {
              this.resultData.push({
                type: 'user',
                children: users
              })
            }
            let tags = res.rows.filter(item => item.flag == 2).map(item => {
              return {id: item.id, label: item.name, type: 'tag'}
            })
            if (tags.length) {
              this.resultData.push({
                type: 'tag',
                children: tags
              })
            }

          } else {
            this.resultData = []
          }
        }
      })
      if (this.values.length) {
        this.updateCheckbox(this.resultData, 'list')
      }
      this.isSearch = true
    },
    getTags() {
      this.tags = []
      listTip().then(res => {
        if (res.code == '200') {
          if (res.rows && res.rows.length) {
            this.tags = res.rows.map(item => {
              return {
                id: item.id,
                label: item.name
              }
            })
          }
        }
      })
    },
    checkItem(item, type) {
      // console.log(item)
      let f_index = this.values.findIndex(fItem => fItem.id == item.id)
      if (f_index > -1) {
        this.$set(item, 'checked', false);
        this.values.splice(f_index, 1)
      } else {
        this.$set(item, 'checked', true);
        this.values.push({
          type: type || item.type,
          id: item.id,
          label: item.label
        })
      }
      // console.log(this.values)
    },
    deleteItem(item) {
      let f_index = this.values.findIndex(fItem => fItem.id == item.id)
      this.values.splice(f_index, 1)
      if (!this.isSearch) {
        if (item.type == 'tag') {
          this.updateCheckbox(this.tags, 'list')
        }
        if (item.type == 'org' || item.type == 'user') {
          if (this.$refs.orgTree.getNode(item.id).data) {
            this.$refs.orgTree.getNode(item.id).data.checked = false
          }
        }
      } else {
        this.updateCheckbox(this.resultData, 'list')
      }

    },
    updateCheckbox(data, type) {
      if (data && data.length) {
        // console.log('data', data)
        data.forEach(item => {
          let f_index = this.values.findIndex(fitem => {
            return (fitem.id == item.id)
          })
          if (item.id) {
            if (type == 'tree') {
              this.$refs.orgTree.getNode(item.id).data.checked = f_index > -1 ? true : false
            }
            if (type == 'list') {
              this.$set(item, 'checked', f_index > -1 ? true : false);
            }
          }
          if (item.children && item.children.length) {
            this.updateCheckbox(item.children, type)
          }
        })
      }
    },
    getOrgTreeAll() {
      treeselectAll().then(res => {
        if (res.code == '200') {
          this.orgTree = res.data ? res.data : [];
          if(this.maxLevel){
            this.orgTree = this.getLevelData(this.orgTree,0,this.maxLevel)
          }
          this.initData(this.orgTree)
          // console.log(this.orgTree)
          this.defaultExpandedKeys = [this.orgTree[0].id]
          this.getUsers(this.orgTree[0])
        }
      })
    },
    //获取组织结构
    getOrgTree() {
      treeselect(this.queryParams).then(res => {
        if (res.code == '200') {
          this.orgTree = res.data ? res.data : [];
          if(this.maxLevel){
            this.orgTree = this.getLevelData(this.orgTree,0,this.maxLevel)
          }
          this.initData(this.orgTree)
          // console.log(this.orgTree)
          this.defaultExpandedKeys = [this.orgTree[0].id]
          this.getUsers(this.orgTree[0])
        }
      })
    },
    // 初始化data
    initData(data){
      if(data.length) {
        data.forEach(item => {
          if(item.children) {
            item.totalNum = this.count(item.children, item.num)
            this.initData(item.children)
          }else{
            item.totalNum  = item.num
          }
        })
      }
    },
    // 获取组织架构前n层数据
    getLevelData(data, currentLevel = 0, maxLevel) {
      if (currentLevel >= maxLevel) {
        return [];
      }
      return data.map((item) => {
        const newItem = { ...item, level:currentLevel };
        if (newItem.children) {
          newItem.children = this.getLevelData(newItem.children, currentLevel + 1, maxLevel);
        }
        return newItem;
      });
    },
    // count 部门人数
    count(data,num){
      if(data.length) {
        for(let i = 0; i<data.length; i++){
          num =  num + data[i].num
          if(data[i].children){
            num = this.count(data[i].children,num)
          }
        }
        return num  || 0
      }
    },
    handleNodeClick(data) {
      if (!data.leaf) {
        this.getUsers(data)
      }  else if (!data.leaf && data.checked) {
        this.checkItem(data, 'org')
      } else if (data.leaf) {
        this.checkItem(data, 'user');
      }
      this.defaultExpandedKeys = [data.id]
    },
    expandNode(data) {
      this.getUsers(data)
    },
    getUsers(data){
      if(this.maxLevel && data.level + 1 >= this.maxLevel){
        return
      }
      getUsersByDeptId(data.id).then(res => {
        if (res.code == '200' && res.rows && res.rows.length) {
          for (let i = 0; i < res.rows.length; i++) {
            const newChild = {id: res.rows[i].userId, label: res.rows[i].userName, leaf: true};
            if (!data.children) {
              this.$set(data, 'children', []);
            }
            if(data.children.filter(item=>item.label == newChild.label && item.id == newChild.id).length == 0){
              data.children.push(newChild);
            }
          }
        }
      })
    }
  },
  created() {
    console.log(this.useTreeAll);
    if(this.useTreeAll) {
       this.getOrgTreeAll();
    } else{
      this.getOrgTree();
    }
   
    this.getTags();
    this.fieldValues =  JSON.parse(JSON.stringify(this.pickArray))
    this.values = JSON.parse(JSON.stringify(this.pickArray))
  }
}
</script>

<style scoped lang="scss">
@import '../../assets/styles/org-tree.scss';
</style>
